package com.suixinsanren.design.iterator.demo02;

import java.util.Arrays;

public class DinerMenuIterator implements Iterator<MenuItem> {

    private MenuItem[] menuItems;
    private int position = 0;

    public DinerMenuIterator(MenuItem[] menuItems) {
        this.menuItems = menuItems;
    }

    @Override
    public boolean hasNext() {
        return position < menuItems.length && menuItems[position] != null;
    }

    @Override
    public MenuItem next() {
        return menuItems[position++];
    }

    /**
     * remove无参数是删除当前元素，但是使用next获取元素后position就++了，所以只能删除前一个元素
     * 删除后position必须--
     */
    @Override
    public void remove() {
        if (position <= 0) {
            System.out.println("删除失败");
        }
        for (int i = position - 1; i < menuItems.length - 1; i++) {
            menuItems[i] = menuItems[i + 1];
        }
        position--;
    }
}
